package com.dream.common;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.poi.ss.formula.functions.T;

import freemarker.template.Configuration;
import freemarker.template.Template;

@SuppressWarnings("all")
public class FreemakerUtil {

	public static void createJavaFile(String tableName,Map<String, Object> map,String basePackage,String basePath) {

		try {
			
			StringBuffer sb = new StringBuffer(basePath);
			sb.append("\\resource\\");

			Configuration config = new Configuration();
			config.setDirectoryForTemplateLoading(new File(sb.toString()));

			Template t = config.getTemplate("entity.ftl");

			File f = new File(basePath + "\\src\\" + basePackage.replaceAll("\\.", "/") + "\\" + capStrFirst(tableName) + ".java");
			System.out.println(basePath + "\\src\\" + basePackage.replaceAll("\\.", "/") + "\\" + capStrFirst(tableName) + ".java");
			if (f.exists()) {
				f.delete();
			}
			f.createNewFile();
			Writer writer = new FileWriter(f);
			t.process(map, writer);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("生成java文件失败: "+capStrFirst(tableName));
		}
	}
	public static String capStrFirst(String str){
		StringBuffer sb = new StringBuffer();
		String[] arr = str.split("_");
		for(String s : arr){
			s = s.substring(0, 1).toUpperCase() + s.substring(1);
			sb.append(s).append("_");
		}
		String result = sb.toString();
		if(result.contains("_")){
			result = result.substring(0, result.lastIndexOf("_"));
		}
		return result;
	}
	public static String lowStr(String str){
		return str.toLowerCase();
	}
	public static String lowStrFirst(String str){
		StringBuffer sb = new StringBuffer();
		String[] arr = str.split("_");
		for(String s : arr){
			s = s.substring(0, 1).toLowerCase() + s.substring(1);
			sb.append(s).append("_");
		}
		String result = sb.toString();
		if(result.contains("_")){
			result = result.substring(0, result.lastIndexOf("_"));
		}
		return result;
	} 
}
